package com.sgb.businessmodule.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.barlibrary.ImmersionBar;
import com.harisucici.jetpackbase.base.HBaseActivity;
import com.sgb.businessmodule.BR;
import com.sgb.businessmodule.R;
import com.sgb.businessmodule.databinding.ActivityBusinessSearchBinding;
import com.sgb.businessmodule.view.ui.adapter.BusinessSearchFlowLayoutAdapter;
import com.sgb.businessmodule.view.ui.adapter.KeyWordSearchAdapter;
import com.sgb.businessmodule.view.widget.MyItemDecoration;
import com.sgb.businessmodule.viewmodel.BusinessOpportunityHallModel;
import com.sgb.businessmodule.viewmodel.BusinessSearchModel;
import com.swgk.core.base.AppActivity;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.recyclerview.FlowLayoutManager;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.List;

/**
 * 商机搜索界面
 * LiWei  2021/8/16
 */
@Route(path = AppRouteConstant.ShangJi.ROUTER_PATH_SJ_BUSINESS_SEARCH)
public class BusinessSearchActivity extends HBaseActivity<ActivityBusinessSearchBinding, BusinessSearchModel> implements View.OnClickListener {
    private BusinessSearchFlowLayoutAdapter historyAdapter;
    private KeyWordSearchAdapter keyWordSearchAdapter;

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, BusinessSearchActivity.class);
        context.startActivity(intent);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .fitsSystemWindows(false)
                .keyboardEnable(false)
                .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
                .init();
        return R.layout.activity_business_search;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData(View v) {
        initView();
        initData();
    }

    /**
     * view 初始化
     */
    private void initView() {
        binding.topLayout.ivBack.setOnClickListener(this::onClick);
        binding.topLayout.tvSearch.setOnClickListener(this::onClick);
        binding.ivDeleteHistory.setOnClickListener(this::onClick);
        binding.topLayout.tvSearch.setOnClickListener(this::onClick);
        initEtSearchView();
        initLiveDataListener();

        keyWordSearchAdapter = new KeyWordSearchAdapter(this, null);
        binding.keywordRecycler.setLayoutManager(new LinearLayoutManager(this));
        binding.keywordRecycler.addItemDecoration(new RecyclerCustomDecoration(0,
                0,
                0,
                getResources().getDimension(R.dimen.dp1)));
        binding.keywordRecycler.setAdapter(keyWordSearchAdapter);
        keyWordSearchAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
                loadData(s);
            }
        });
    }

    /**
     * 界面数据初始化
     */
    private void initData() {
        if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            viewModel.requestHistorySearchData();
        } else {
            initHistory(viewModel.getHistorySearchList());
        }
    }

    /**
     * 初始化键盘搜索功能
     */
    private void initEtSearchView() {
        binding.topLayout.etView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    loadData(getKeyWord());
                }
                return false;
            }
        });
        binding.topLayout.etView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                viewModel.requestKeywordSearchData(s.toString());
            }
        });
    }

    /**
     * LiveData 数据业务监听
     */
    private void initLiveDataListener() {
        //搜索历史数据返回监听
        viewModel.historySearchList.observe(this, list -> initHistory(list));
        //删除搜索历史数据返回监听
        viewModel.deleteSearchStatus.observe(this, aBoolean -> {
            if (aBoolean) {
                deleteSuccess();
            }
        });
        //关键字搜索数据返回监听
        viewModel.keywordData.observe(this, new Observer<List<String>>() {
            @Override
            public void onChanged(List<String> strings) {
                keyWordSearchAdapter.setDatas(strings);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back) {
            finish();
        } else if (v.getId() == R.id.tv_search) {
            loadData(getKeyWord());
        } else if (v.getId() == R.id.iv_delete_history) {
            if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                viewModel.deleteHistorySearchData();
            } else {
                if (viewModel.clearHistorySearchData()) {
                    deleteSuccess();
                }
            }

        }
    }

    /**
     * 获取当前搜索框的关键词
     */
    private String getKeyWord() {
        return binding.topLayout.etView.getText().toString().trim();
    }

    /**
     * 执行搜索跳转操作
     */
    private void loadData(String mKeyWord) {
        if (TextUtils.isEmpty(mKeyWord)) {
            MToast.showToast(this, "请输入商机关键词");
            return;
        }
        viewModel.setShardHistorySearch(mKeyWord);
        BusinessOpportunityHallActivity.start(this, mKeyWord);
        finish();
    }

    /**
     * 删除历史搜索数据处理
     */
    private void deleteSuccess() {
        if (historyAdapter != null) {
            historyAdapter.clearDatas();
        }
        binding.tvNullData.setVisibility(View.VISIBLE);
    }

    /**
     * 历史搜索数据配置
     *
     * @param historySearchList 历史搜索数据
     */
    private void initHistory(List<String> historySearchList) {
        if (historySearchList == null) {
            binding.rvHistory.setVisibility(View.GONE);
            binding.tvNullData.setVisibility(View.VISIBLE);
            return;
        } else {
            binding.rvHistory.setVisibility(View.VISIBLE);
            binding.tvNullData.setVisibility(View.GONE);
        }
        historyAdapter = new BusinessSearchFlowLayoutAdapter(this, historySearchList);
        binding.rvHistory.setLayoutManager(new FlowLayoutManager());
        binding.rvHistory.addItemDecoration(new MyItemDecoration(this));
        binding.rvHistory.setAdapter(historyAdapter);
        historyAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String keyword, int position) {
                loadData(keyword);
            }
        });
    }


}
